package com.xiaojie.consumer;


import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.xiaojie.entity.Dispatch;
import com.xiaojie.mapper.DispatchMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author xiaojie
 * @version 1.0
 * @description: 派单消费者
 * @date 2021/10/11 22:58
 */
@Component
public class DispatchConsumer {
    @Autowired
    private DispatchMapper dispatchMapper;
    @RabbitListener(queues = "dispatch_order_queue")
    public void dispatchConsumer(Message message, Channel channel) throws IOException {
        // 1.获取消息
        String msg = new String(message.getBody());
        // 2.转换json
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String orderId = jsonObject.getString("orderId");
        // 计算分配的快递员id
        Dispatch dispatch=new Dispatch();
        dispatch.setOrderId(orderId);
        //经过一系列的算法得到送餐时间为30分钟
        dispatch.setSendTime(30*60L);
        dispatch.setRiderId(1000012L);
        dispatch.setUserId(15672L);
        // 3.插入我们的数据库
        int result = dispatchMapper.saveDispatch(dispatch);
        if (result > 0) {
            // 手动ack 删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
